package com.shenzhen.horselive.common;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Environment;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.Target;
import com.flqy.baselibrary.utils.FileUtils;

import java.io.File;

public class ImageCacheAsyncTask extends AsyncTask<String, Void, Bitmap> {

    private final Context context;

    public ImageCacheAsyncTask(Context context) {
        this.context = context;
    }

    @Override
    protected Bitmap doInBackground(String... params) {
        String imgUrl = params[0];
        try {
            return Glide.with(context)
                    .asBitmap()
                    .load(imgUrl)
                    .centerInside()
                    .submit(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL)
                    .get();
        } catch (Exception ex) {
            ex.printStackTrace();
            return null;
        }
    }

    @Override
    protected void onPostExecute(Bitmap result) {
        if (result == null) {
            return;
        }
        //notifySystem(FileUtils.savaImage(result, context.getExternalFilesDir(Environment.DIRECTORY_PICTURES).getPath()));
        notifySystem(FileUtils.savaImage(result, Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).getPath()));
    }

    private void notifySystem(String filePath) {
        Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
        Uri uri = Uri.fromFile(new File(filePath));
        intent.setData(uri);
        context.sendBroadcast(intent);
    }
}